package org.pz.http;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * http 相关的工具类
 * */
@Slf4j
public class HttpUtils {

    /**
     * 通过 response 响应 json 数据
     * */
    public static void parseResponseBody(String jsonString, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try(PrintWriter writer = response.getWriter()){
            writer.append(jsonString);
        }catch (IOException e){
            log.error("parserResponseBody 发生 io 异常", e);
        }
    }

    /**
     * 从 request 中获取 json 数据
     * */
    public static JSONObject getJsonObjectFromRequest(HttpServletRequest request){
        StringBuilder sb = new StringBuilder();
        try(BufferedReader reader = request.getReader()){
            String line;
            while( (line = reader.readLine()) != null ){
                sb.append(line).append("\n");
            }
        }catch(IOException e){
            log.error("getJsonObjectFromRequestBody 发生 io 异常", e);
        }
        return JSONObject.parseObject(sb.toString());
    }

    /**
     * 获取请求方法 GET,POST
     * */
    public static String getMethod(HttpServletRequest request){
        return request.getMethod().toUpperCase();
    }
}
